<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class VoteWorks
 *
 * @package App\Models
 * @property int $id
 * @property int $vote_id
 * @property int $works_id
 * @property int $vote_award_id
 * @property int $score
 * @property-read \App\Models\Vote $vote
 * @property-read \App\Models\Works $works
 * @property-read \App\Models\VoteAward $voteAward
 * @method static \Illuminate\Database\Query\Builder|\App\Models\VoteWorks whereVoteId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\VoteWorks whereWorksId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\VoteWorks whereVoteAwardId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\VoteWorks whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\VoteWorks whereScore($value)
 * @mixin \Eloquent
 */
class VoteWorks extends Model
{
    protected $table = 'vote_works';

    public $timestamps = false;


    /**
     * 投票池
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function vote()
    {
        return $this->belongsTo('\App\Models\Vote', 'vote_id');
    }


    /**
     * 作品
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function works()
    {
        return $this->belongsTo('\App\Models\Works', 'works_id');
    }


    /**
     * 奖项
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function voteAward()
    {
        return $this->belongsTo('\App\Models\VoteAward', 'vote_award_id');
    }

    /**
     * 更新投票数
     */
    public function updateScore()
    {
        try {
            $this->score = VoteDetail::where('vote_id', $this->vote_id)
                ->where('works_id', $this->works_id)
                ->sum('score');
            $this->save();
        } catch (\Exception $e) {
            \Log::error('更新投票数失败.', $this->toArray());
        }
    }

    /**
     * 设置奖项
     * @param int $voteAwardId
     */
    public function setVoteAward($voteAwardId , $type)
    {
        try {
            $this->vote_award_id = $voteAwardId;
            $this->save();
            if ($type == 1){
                $this->works->second_vote_award_id = $voteAwardId;
            }else{
                $this->works->vote_award_id = $voteAwardId;
            }
            $this->works->save();
        } catch (\Exception $e) {
            \Log::error('奖项设置出错.' . $e->getMessage());
        }
    }
}